package com.cn.sys.main.servlet;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import com.cn.sys.common.Constants;
import com.cn.sys.frame.util.PropertiesUtil;
import com.cn.sys.frame.util.SpringContextUtil;

public class InitDataServlet extends HttpServlet {

	private static final long serialVersionUID = 3760047764182865115L;

	private static final Logger logger = LoggerFactory.getLogger(InitDataServlet.class);
	
	public void init(ServletConfig config) throws ServletException {
		logger.info("InitDataServlet  start !!!");
		checkDataBaseInfo();
	}

	private void checkDataBaseInfo(){
		try {
			DataSource ds = SpringContextUtil.getBean("dataSource");
			//logger.info("数据库连接池:"+ds.getClass());
			DatabaseMetaData dbmd = ds.getConnection().getMetaData();
			String dbName = dbmd.getDatabaseProductName();
			//logger.info("通过JDBC获取的数据库类型:"+dbName+"  版本:"+dbmd.getDatabaseMajorVersion());
			Constants.SYS_DB_TYPE = dbName.toUpperCase();
			//logger.info("数据库类型:"+Constants.SYS_DB_TYPE);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("获取数据库信息出错! "+e.getMessage());
		}
	}
	/**
	 * 检查表主键的最大值和与之对应的序列的下一个值,序列的下一个值应该大于表的最大值,根据实际情况可以决定是否需要检查
	 */
	private void checkSequenceNextValue(){
		try {
			DataSource ds = SpringContextUtil.getBean("dataSource");
			DatabaseMetaData dbmd = ds.getConnection().getMetaData();
			PropertiesUtil pu = new PropertiesUtil();
			String userName = pu.getValue("jdbc.user").toUpperCase();
			ResultSet tbrs = dbmd.getTables(null, userName, null, new String[]{"TABLE"});
			JdbcTemplate jdbcTemplate = SpringContextUtil.getBean("jdbcTemplate");
			while (tbrs.next()) {
				String tableName = tbrs.getString("TABLE_NAME");
				String sequenceName = "SEQ_"+tableName;
				ResultSet pkrs = dbmd.getPrimaryKeys(null, userName, tableName);
				String pkName = "";
				while (pkrs.next()) {
					pkName = pkrs.getString("COLUMN_NAME");
					break;
				}
				if(StringUtils.isBlank(pkName)){
					pkName = "ID";
				}
				long tableMaxValue = jdbcTemplate.queryForLong("SELECT MAX("+pkName+") MAXVALUE FROM "+tableName);
				long sequenceNextValue = jdbcTemplate.queryForLong("SELECT "+sequenceName+".NEXTVAL FROM DUAL");
				logger.info(tableName+"主键的最大值为:"+tableMaxValue+"   对应的序列"+sequenceName+"下一值:"+sequenceNextValue);
				for (long i = sequenceNextValue; i <= tableMaxValue; i++) {
					jdbcTemplate.queryForLong("SELECT "+sequenceName+".NEXTVAL FROM DUAL");
				}
			}
			logger.info("检查序列的下一值完成!");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("InitDataServlet  error!!!["+e.getMessage()+"]");
		}
	}
	public void destroy() {
		logger.info("InitDataServlet  destroy !!!");
	}
}
